<?php
/**
* 奇门接口请求
* @author fengcong
* @date 2018.03.28
* @copyright qianjiangcloud.com
*/
class erpapi_rpc_qimen 
{
    
    /*
    * 请求
    * @param string $method 接口方法
    * @param array $params
    * @return array 接口返回
    */
    public function call($method, $params)
    {
        $innerRs = array('GetStatus' => '0', 'GetError' => '');

        //组装系统参数
        $sysParams["app_key"] ="24818626";
        $sysParams['target_app_key'] = $sysParams["app_key"];
        $sysParams["v"] = '2.0';
        $sysParams["format"] = 'json';
        $sysParams["sign_method"] = 'md5';
        $sysParams["method"] = 'lm.other.apis';
        $sysParams["timestamp"] = date("Y-m-d H:i:s");

        // if (!in_array($method, ['X3_Cancel_Order', 'X3_Cancel_VpOrder'])){
        //     $dataJson = json_encode($params, JSON_UNESCAPED_UNICODE);
        //     $dataJson = '<data_json>'.$dataJson.'</data_json>';
        // } else {
        //     $dataJson = $params;
        //     $dataJson = kernel::single('base_xml')->arrayToXml($dataJson);
        // }

        // $submit = '';
        // if ($method == 'X3_Input_MoveNotice') {
        //     //调拨通知，头增加submit=0
        //     $submit = '<submit>0</submit>';
        // }

        $apiParams = array(
            'api_data' => json_encode($params),
            'api_method' => $method
        );
        //系统参数放入GET请求串
        
        $requestUrl = app::get('ome')->getConf('ome.open.erp.qimen.url');;

        //签名
        $params = array_merge($apiParams, $sysParams);
        $sysParams["sign"] = $this->getSign($params);

        foreach ($sysParams as $sysParamKey => $sysParamValue)
        {
            $requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
        }

        $fileFields = array();
        foreach ($apiParams as $key => $value) {
            if(is_array($value) && array_key_exists('type',$value) && array_key_exists('content',$value) ){
                $value['name'] = $key;
                $fileFields[$key] = $value;
                unset($apiParams[$key]);
            }
        }

        // $requestUrl .= "timestamp=" . urlencode($sysParams["timestamp"]) . "&";
        $requestUrl = substr($requestUrl, 0, -1);

        //发起HTTP请求
        try
        {
            $resp = $this->curl($requestUrl, $apiParams);
            
        }
        catch (Exception $e)
        {
        }
        return $resp;
    }

    /**
    * 签名
    * @param array $params 接口参数
    * @return string md5 签名
    */
    private function getSign($params)
    {
        ksort($params);
        $secretKey = 'd427ac93a7e8e6ea466566f719ab03ee';
        $stringToBeSigned = $secretKey;
        foreach ($params as $k => $v)
        {
            if(is_string($v) && "@" != substr($v, 0, 1))
            {
                $stringToBeSigned .= "$k$v";
            }
        }
        unset($k, $v);
        $stringToBeSigned .= $secretKey;

        $sign = strtoupper(md5($stringToBeSigned));
        return $sign;
    }

    /**
    * 奇门curl请求
    * @param string $url 请求url
    * @param array $postFields 请求参数
    * @return array 奇门返回结果
    */
    private function curl($url, $postFields = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt ( $ch, CURLOPT_USERAGENT, "top-sdk-php" );
        //https 请求
        if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        if (is_array($postFields) && 0 < count($postFields))
        {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v)
            {
                if(!is_string($v))
                    continue ;

                if("@" != substr($v, 0, 1))//判断是不是文件上传
                {
                    $postBodyString .= "$k=" . urlencode($v) . "&"; 
                }
                else//文件上传用multipart/form-data，否则用www-form-urlencoded
                {
                    $postMultipart = true;
                    if(class_exists('\CURLFile')){
                        $postFields[$k] = new \CURLFile(substr($v, 1));
                    }
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart)
            {
                if (class_exists('\CURLFile')) {
                    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
                } else {
                    if (defined('CURLOPT_SAFE_UPLOAD')) {
                        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
                    }
                }
        error_log(date('Y-m-d H:i:s') . '发送数据/' . var_export($postFields, true), 3, DATA_DIR . '/AXToOMs_' . date('Y-m-d') . '.log');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            }
            else
            {
                $header = array("content-type: application/x-www-form-urlencoded; charset=UTF-8");
                curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
            }
        }
        $reponse = curl_exec($ch);
        
        if (curl_errno($ch))
        {
            throw new Exception(curl_error($ch),0);
        }
        else
        {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode)
            {
                throw new Exception($reponse,$httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }

}
